package cn.topcodes.tcsf.admin.service.impl;

import cn.topcodes.tcsf.admin.commons.generic.GenericService;
import cn.topcodes.tcsf.admin.commons.generic.Logable;
import cn.topcodes.tcsf.admin.domain.entity.SysOperateLog;
import cn.topcodes.tcsf.admin.service.log.SysOperateLogService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class SysOperateLogServiceImpl extends GenericService<SysOperateLog> implements SysOperateLogService,Logable {

    private ThreadLocal<String> ip = new ThreadLocal<String>();

    private ThreadLocal<Boolean> ready = new ThreadLocal<Boolean>() {
        @Override
        protected Boolean initialValue() {
            return false;
        }
    };

    private ThreadLocal<Integer> level = new ThreadLocal<Integer>() {
        @Override
        protected Integer initialValue() {
            return 0;
        }
    };

    @Override
    public void readyLog() {
        ready.set(true);
        level.set(0);
    }

    @Override
    public int incLevel() {
        this.level.set(this.level.get() + 1);
        return this.level.get();
    }

    @Override
    public int decLevel() {
        this.level.set(this.level.get() - 1);
        return this.level.get();
    }

    @Override
    public int getLevel() {
        return this.level.get();
    }

    public void setIp(String ip) {
        this.ip.set(ip);
    }

    @Override
    @Transactional(readOnly = false)
    public void log(Long userId, String type, String content) {
        //  加上自身事务方法+1，所以判断2
        if(ready.get() && level.get() == 2) {
            this.forceLog(userId, type, content);
        }
    }

    @Override
    @Transactional(readOnly = false)
    public void forceLog(Long userId, String type, String content) {
        SysOperateLog operateLog = new SysOperateLog();
        operateLog.setIp(ip.get());
        operateLog.setContent(content);
        operateLog.setType(type);
        operateLog.setUserId(userId);
        this.create(operateLog);
    }
}
